package cn.liyicun.test.controller;

import cn.liyicun.test.base.Common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class BaseController {

    protected long isLogin(HttpServletRequest req, HttpServletResponse res, boolean flag) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            if (flag) {
                try {
                    res.sendRedirect("/login");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return 0;
        }

        Object userid = session.getAttribute(Common.USER_SESSION_NAME);
        if (userid == null) {
            if (flag) {
                try {
                    res.sendRedirect("/login");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return 0;
        }

        return (long) userid;
    }

    protected long isLogin(HttpServletRequest req, HttpServletResponse res) throws IOException {
        return isLogin(req, res, false);
    }


    protected boolean _captcha(HttpServletRequest req, String captcha) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            return false;
        }
        Object userid = session.getAttribute(Common.CAPTCHA_NAME);
        if (userid != null) {
            session.removeAttribute(Common.CAPTCHA_NAME);
            return captcha.equalsIgnoreCase(userid.toString());
        }
        return false;
    }
}
